package org.gitee.weapp.controller;

import org.apache.commons.lang3.StringUtils;
import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.entity.Coupon;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.mapper.CouponMapper;
import org.gitee.weapp.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TokenService tokenService;

    @RequestMapping("/list")
    public AjaxResult getCouponList(@RequestParam("isExpired") Boolean isExpired) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }
        List<Coupon> couponList = couponMapper.getCouponList(sysUser.getOpenId(), isExpired);
        return AjaxResult.success(couponList);
    }

    @PostMapping("/bind")
    public AjaxResult bindCoupon(@RequestParam("couponId") String couponId) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }

        Coupon coupon = couponMapper.getCouponById(couponId);
        if (null == coupon || (null != coupon.getUserId() && !coupon.getUserId().equals(sysUser.getOpenId()))) {
            return AjaxResult.error("优惠券不存在");
        }
        if (coupon.getUsed()) {
            return AjaxResult.error("优惠券已使用");
        }
        if (StringUtils.equals(coupon.getUserId(), sysUser.getOpenId())) {
            return AjaxResult.error("不可重复兑换");
        }

        coupon.setUserId(sysUser.getOpenId());
        couponMapper.update(coupon);
        return AjaxResult.success("兑换成功");
    }
}
